package com.livew.framework.base.service.impl;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.livew.framework.base.dao.BaseMapper;
import com.livew.framework.base.dao.FileMapper;
import com.livew.framework.base.model.FileEO;
import com.livew.framework.base.service.FileService;
import com.livew.framework.exception.XTBusinessException;
import com.livew.framework.fastdfs.ConstantUtil;
import com.livew.framework.fastdfs.DfsHandler;
import com.livew.framework.utils.DeleteType;
import com.livew.framework.utils.XTCurrentUser;
import com.livew.framework.utils.XTEntityUtils;
import com.livew.framework.utils.XTListUtils;
import com.livew.framework.utils.XTStringUtils;
import com.livew.framework.utils.XTUnitUtils;

@Service
public class FileServiceImpl extends BaseServiceImpl<FileEO> implements FileService {

	@Resource
	private FileMapper fileMapper;

	public FileServiceImpl(BaseMapper<FileEO> baseMapper) {
		super(baseMapper);
	}

	@Override
	public void saveFiles(List<FileEO> files) throws XTBusinessException {
		if (XTListUtils.isEmpty(files)) {
			throw new XTBusinessException("参数错误");
		}
		for (FileEO FileEO : files) {
			FileEO.setCreateTime(new Date());
			FileEO.setCreateUserId(XTCurrentUser.getCurrentUserId());
		}
		fileMapper.insertFilesSelective(files);
	}

	@Override
	public void updateBySrcName(FileEO FileEO) throws XTBusinessException {
		if (FileEO == null || XTStringUtils.isEmpty(FileEO.getSrcname())) {
			throw new XTBusinessException("参数错误");
		}
		if (XTStringUtils.isEmpty(FileEO.getCaseClazz()) || FileEO.getCaseId() == null) {
			throw new XTBusinessException("参数错误");
		}
		FileEO.setUpdateTime(new Date());
		FileEO.setUpdateUserId(XTCurrentUser.getCurrentUserId());
		fileMapper.delBySrcName(FileEO);
		fileMapper.updateBySrcName(FileEO);
	}

	@Override
	public void delBySrcName(FileEO FileEO) throws XTBusinessException {
		if (FileEO == null || XTStringUtils.isEmpty(FileEO.getSrcname())) {
			throw new XTBusinessException("参数错误");
		}
		List<FileEO> files = fileMapper.selectListByCondition(FileEO);
		if (XTListUtils.isEmpty(files)) {
			throw new XTBusinessException("参数错误");
		}
		FileEO.setUpdateTime(new Date());
		FileEO.setUpdateUserId(XTCurrentUser.getCurrentUserId());
		fileMapper.delFileBySrcName(FileEO);
	}

	@Override
	public Map<Long, List<FileEO>> getListToMap(List<Long> caseIds, String caseClazz, String type) {
		Map<Long, List<FileEO>> map = new HashMap<Long, List<FileEO>>();
		if (XTListUtils.isEmpty(caseIds) || XTStringUtils.isEmpty(caseClazz)) {
			return map;
		}
		FileEO FileEO = new FileEO();
		FileEO.setCaseClazz(caseClazz);
		FileEO.setCaseIds(caseIds);
		FileEO.setType(type);
		List<FileEO> files = fileMapper.selectListByByCaseIds(FileEO);
		if (!XTListUtils.isEmpty(files)) {
			List<FileEO> list = null;
			for (FileEO file2 : files) {
				List<FileEO> tempList = map.get(file2.getCaseId());
				if (XTListUtils.isEmpty(tempList)) {// 第一次添加
					list = new ArrayList<>();
					list.add(file2);
					map.put(file2.getCaseId(), list);
				} else {
					tempList.add(file2);
				}
			}
		}
		return map;
	}

	@Override
	public List<FileEO> getList(List<Long> caseIds, String caseClazz, String type) {
		List<FileEO> list = null;
		if (XTListUtils.isEmpty(caseIds) || XTStringUtils.isEmpty(caseClazz)) {
			return list;
		}
		FileEO FileEO = new FileEO();
		FileEO.setCaseClazz(caseClazz);
		FileEO.setCaseIds(caseIds);
		FileEO.setType(type);
		List<FileEO> files = fileMapper.selectListByByCaseIds(FileEO);
		return files;
	}

	@Override
	public Map<Long, FileEO> getMapTopOne(List<Long> caseIds, String caseClazz, String type) {
		Map<Long, FileEO> map = new HashMap<Long, FileEO>();
		if (XTListUtils.isEmpty(caseIds) || XTStringUtils.isEmpty(caseClazz)) {
			return map;
		}
		FileEO FileEO = new FileEO();
		FileEO.setCaseClazz(caseClazz);
		FileEO.setCaseIds(caseIds);
		FileEO.setType(type);
		List<FileEO> files = fileMapper.selectListByByCaseIds(FileEO);
		if (!XTListUtils.isEmpty(files)) {
			for (FileEO file2 : files) {
				FileEO temp = map.get(file2.getCaseId());
				if (temp == null) {// 第一次添加
					map.put(file2.getCaseId(), file2);
				}
			}
		}
		return map;
	}

	@Override
	public FileEO insertDfs(MultipartFile FileEO) throws Exception {
		FileEO eo = new FileEO();
		String fileName = FileEO.getOriginalFilename();
		try {
			// 文件上传
			byte[] fileBuffer = FileEO.getBytes();
			DfsHandler handler = DfsHandler.getInstance(ConstantUtil.TRACKER);
			String[] results = handler.upload(fileBuffer);
//			BufferedImage bi = ImageIO.read(FileEO.getInputStream());
//			bi.getWidth();
//			bi.getHeight();
			eo.setGroupname(results[0]);
			eo.setRemotefilename(results[1]);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(fileName + " upload failed.");
		}
		eo.setSrcname(fileName);
		// 计算出文件的大小与现实单位(KB/MB)
		long bytes = FileEO.getSize();// bytes
		String[] arr = XTUnitUtils.byte2kbmb(bytes);
		Double size = Double.valueOf(arr[0]);
		String unit = arr[1];
		eo.setSize(size);
		eo.setUnit(unit);
		eo.setCreateTime(new Date());
		eo.setIsDel(DeleteType.IS_NOT_DELETE);
		fileMapper.insertSelective(eo);
		return eo;
	}

	@Override
	public void insertDfs(FileEO FileEO, byte[] byteArray) throws Exception {
		if (FileEO == null || byteArray == null || byteArray.length <= 0) {
			throw new Exception("insertDfs   文件错误");
		}
		if (XTStringUtils.isEmpty(FileEO.getSrcname())) {
			throw new Exception("insertDfs   文件名错误");
		}
		try {
			// 文件上传
			DfsHandler handler = DfsHandler.getInstance(ConstantUtil.TRACKER);
			String[] results = handler.upload(byteArray);
			FileEO.setGroupname(results[0]);
			FileEO.setRemotefilename(results[1]);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("insertDfs   文件错误");
		}
		// 计算出文件的大小与现实单位(KB/MB)
		long bytes = byteArray.length;// bytes
		String[] arr = XTUnitUtils.byte2kbmb(bytes);
		Double size = Double.valueOf(arr[0]);
		String unit = arr[1];
		FileEO.setSize(size);
		FileEO.setUnit(unit);
		FileEO.setCreateTime(new Date());
		FileEO.setIsDel(DeleteType.IS_NOT_DELETE);
		fileMapper.insertSelective(FileEO);
	}

	@Override
	public List<FileEO> getFileById(Long caseId, String caseClazz, String type) {
		FileEO f = new FileEO();
		f.setCaseClazz(caseClazz);
		f.setCaseId(caseId);
		f.setType(type);
		List<FileEO> list = fileMapper.selectListByCondition(f);
		return list;
	}

	@Override
	public List<FileEO> getFileByIds(List<Long> caseIds, String caseClazz, String type) {
		FileEO f = new FileEO();
		f.setCaseClazz(caseClazz);
		f.setCaseIds(caseIds);
		f.setType(type);
		List<FileEO> list = fileMapper.selectListByCondition(f);
		return list;
	}

	@Override
	public List<Long> getFileByCaseId(Long caseId, String caseClazz, String type) {
		FileEO f = new FileEO();
		f.setCaseClazz(caseClazz);
		f.setCaseId(caseId);
		f.setType(type);
		List<FileEO> list = fileMapper.selectListByCondition(f);
		if (!XTListUtils.isEmpty(list)) {
			return XTEntityUtils.getIdList(list);
		}
		return null;
	}

	@Override
	public void updateList(List<Long> ids, Long caseId, String caseClazz) throws XTBusinessException {
		FileEO f1 = new FileEO();
		f1.setCaseClazz(caseClazz);
		f1.setCaseId(caseId);
		List<Long> dels = null;
		List<FileEO> oldList = this.fileMapper.selectListByCondition(f1);
		if(!XTListUtils.isEmpty(oldList)) {
		List<Long> fileIds =	XTEntityUtils.getIdList(oldList);
		dels = new ArrayList<>();
		dels.addAll(fileIds);
		dels.removeAll(ids);//要删除的
		if(!XTListUtils.isEmpty(ids)) {
			ids.removeAll(fileIds);//要新增的
		}
		}
		if (!XTListUtils.isEmpty(ids)) {//要新增的
			if(!XTListUtils.isEmpty(ids)) {
				ids.remove(null);
			}
			for (Long long1 : ids) {
				FileEO f = new FileEO();
				f.setCaseClazz(caseClazz);
				f.setCaseId(caseId);
				f.setId(long1);
				this.updateByPrimaryKeySelective(f);
			}
		}
		if(!XTListUtils.isEmpty(dels)) {
			for (Long id : dels) {
				FileEO f = new FileEO();
				f.setId(id);
				this.delByPrimaryKey(f);	
			}
		}
	}

}
